// useDark.js
import { ref, onMounted, onUnmounted } from 'vue'

export function useDark() {
  // 检测系统是否偏好暗色主题
  const isDark = ref(window.matchMedia('(prefers-color-scheme: dark)').matches)

  // 切换暗色主题函数
  const toggleDark = () => {
    isDark.value = !isDark.value
    // 根据新状态添加或移除 dark 类
    if (isDark.value) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }

  // 监听系统主题变化
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  const handleSystemThemeChange = (e) => {
    isDark.value = e.matches
    // 同步DOM类名
    if (e.matches) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }

  // 挂载时添加事件监听器
  onMounted(() => {
    mediaQuery.addEventListener('change', handleSystemThemeChange)
    // 初始化时根据系统主题设置DOM类名
    if (isDark.value) {
      document.documentElement.classList.add('dark')
    }
  })

  // 卸载时移除事件监听器
  onUnmounted(() => {
    mediaQuery.removeEventListener('change', handleSystemThemeChange)
  })

  return {
    isDark,
    toggleDark
  }
}
